<template>
  <el-dialog :model-value="visible" title="产品检测" width="1020" top="20px" :show-close="false"
    :close-on-click-modal="false">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-suffix=":" inline
      label-position="right">
      <el-form-item class="form-item" label="检测工程师">
        <el-input disabled :model-value="form.cuser || user.realName"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="检测时间">
        <el-input disabled :model-value="form.ctime || now"></el-input>
      </el-form-item>
      <el-form-item class="form-item-line" label="客户检测故障" prop="question">
        <el-input type="textarea" :row="4" v-model="form.question"></el-input>
      </el-form-item>
      <el-form-item class="form-item-line" label="检测故障" prop="questionCheck">
        <el-input type="textarea" :row="4" v-model="form.questionCheck"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="质保状态" prop="warrantyCode">
        <zw-select :data="warrantyList" value-key="code" label-key="name" v-model:label="form.warranty"
          v-model:value="form.warrantyCode"></zw-select>
      </el-form-item>
      <el-form-item class="form-item" label="维修站点" prop="repairSiteCode">
        <zw-select :data="repairSiteList" value-key="code" label-key="name" v-model:label="form.repairSite"
          v-model:value="form.repairSiteCode"></zw-select>
      </el-form-item>
      <el-form-item class="form-item-line" label="工时费" prop="workHourPrice">
        <el-input-number :min="0" v-model.number="form.workHourPrice" :precision="2" :step="0.1"></el-input-number>
      </el-form-item>
      <el-form-item class="form-item" label="是否报价" prop="quoteState">
        <el-select v-model="form.quoteState">
          <el-option value="是" label="是"></el-option>
          <el-option value="否" label="否"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="form-item" label="报价日期" prop="quoteDate">
        <zw-date-picker v-model="form.quoteDate"></zw-date-picker>
      </el-form-item>
      <el-form-item class="form-item" label="报价是否确认" prop="isQuoteConfirm">
        <el-select v-model="form.isQuoteConfirm">
          <el-option :value="true" label="是"></el-option>
          <el-option :value="false" label="否"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="form-item" label="确认日期" prop="quoteConfirmDate">
        <zw-date-picker v-model="form.quoteConfirmDate"></zw-date-picker>
      </el-form-item>
      <el-form-item class="form-item-line" label="上传图片">
        <image-gallary :readonly="false" :image-ids="imageIds" @upload="onUpload"
          @remove="onImageRemove"></image-gallary>
      </el-form-item>
    </el-form>
    <create-list-frame title="产品配件清单" inner-control show-operations :columns="columns"
      :table-data="productCheckPartList" :total="productCheckPartList.length">
      <template #buttons>
        <el-button type="primary" @click="onCreateProductPartViewShow">添加产品</el-button>
        <create-product-part-view :visible="createProductPartViewVisible" :product-code="productCode"
          :data="currentProductPart" @close="createProductPartViewVisible = false"
          @save="onSaved"></create-product-part-view>
      </template>
      <template #operations="row">
        <el-button link type="primary" @click="onUpdateProductPart(row)">编辑</el-button>
        <el-button link type="danger" @click="onDeleteProductPart(row)">删除</el-button>
      </template>
    </create-list-frame>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="emits('close', false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import ZwSelect from '@/components/Form/ZwSelect.vue';
import ZwDatePicker from '@/components/Form/ZwDatePicker.vue';
import ImageGallary from '@/components/Form/ImageGallary.vue';
import CreateListFrame from '@/components/CeateFrame/CreateListFrame.vue';
import CreateProductPartView from './CreateProductPartView.vue';
import DateUtil from '@/plugins/date';
import type { OrderProductCheckDTO, OrderProductCheckPriceDTO, OrderProductCheckVO } from '@/server/afterSale/types';
import ApiTree from '@/server/api-tree';
import { DictTypeEnum, type DictVO } from '@/server/dict/types';
import type { UserVO } from '@/server/user/types';
import { reactive, ref, useTemplateRef, watch } from 'vue';
import type { ColumnType } from '@/components/types';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import ElConfirm from '@/components/ElConfirm';
import StoreManager from '@/plugins/storage';
const user = ref<UserVO>(StoreManager.get<UserVO>("user"));
const now = ref<string>(DateUtil.now());
const props = defineProps<{
  orderId: string,
  productCode: string,
  productSn: string,
  visible: boolean
}>();
const emits = defineEmits(["close"])
const form = ref<OrderProductCheckDTO>({
  guid: "",
  orderId: "",
  /**
  * 工单产品SN
  */
  productSn: "",
  /**
   * 客户故障描述
   */
  question: "",
  /**
   * 检测故障
   */
  questionCheck: "",
  /**
   * 质保状态编码
   */
  warrantyCode: "",
  /**
   * 质保状态
   */
  warranty: "",
  /**
   * 维修站点编码
   */
  repairSiteCode: "",
  /**
   * 维修站点
   */
  repairSite: "",
  workHourPrice: 0,
  quoteState: "否",
  quoteDate: "",
  isQuoteConfirm: false,
  quoteConfirmDate: "",
  cuserId: "",
  cuser: "",
  ctime: "",
})
const formRef = useTemplateRef<FormInstance>("formRef")
const rules = reactive<FormRules<OrderProductCheckDTO>>({
  question: [{ required: true, message: "客户故障描述不能为空" }],
  questionCheck: [{ required: true, message: "检测故障不能为空" }],
  warrantyCode: [{ required: true, message: "质保状态不能为空" }],
  repairSiteCode: [{ required: true, message: "维修站点不能为空" }],
  workHourPrice: [{ required: true, message: "工时费不能为空" }, { min: 0, type: "number", message: "工时费不能小于0" }]
})
watch(() => form.value.quoteState, () => {
  if (form.value.quoteState === "是") {
    rules.quoteDate = [{ required: true, message: "报价日期不能为空" }]
  } else {
    rules.quoteDate = []
  }
}, { immediate: true })
watch(() => form.value.isQuoteConfirm, () => {
  if (form.value.isQuoteConfirm) {
    rules.quoteConfirmDate = [{ required: true, message: "报价确认日期不能为空" }]
  } else {
    rules.quoteConfirmDate = []
  }
}, { immediate: true })
/** 质保状态 */
const warrantyList = ref<DictVO[]>([])
const getWarrantyList = async () => {
  const { success, data } = await ApiTree.dict.list(DictTypeEnum.WARRANTY, true);
  if (success) {
    warrantyList.value = data;
  }
}
const repairSiteList = ref<DictVO[]>([])
const getRepairSiteList = async () => {
  const { success, data } = await ApiTree.dict.list(DictTypeEnum.REPAIR_SITE, true);
  if (success) {
    repairSiteList.value = data;
  }
}
/** 附件列表 */
const imageIds = ref<string[]>([])
const onUpload = (data: string[]) => {
  imageIds.value.push(...data);
}
const onImageRemove = (fileId: string) => {
  const index = imageIds.value.findIndex(x => x === fileId);
  imageIds.value.splice(index, 1);
}
/** 产品配件清单 */
const columns = ref<ColumnType[]>([
  { prop: "productPartName", colName: "配件名称", width: 0 },
  { prop: "price", colName: "单价", width: 0 },
  { prop: "count", colName: "数量", width: 0 },
  { prop: "totalPrice", colName: "合计", width: 0 },
])
const productCheckPartList = ref<OrderProductCheckPriceDTO[]>([]);
const createProductPartViewVisible = ref(false);
const currentProductPart = ref<OrderProductCheckPriceDTO | null>(null);
const onCreateProductPartViewShow = () => {
  currentProductPart.value = null;
  createProductPartViewVisible.value = true;
}
const onSaved = (data: OrderProductCheckPriceDTO) => {
  const part = productCheckPartList.value.find(x => x.guid === data.guid);
  if (!part) {
    if (productCheckPartList.value.some(x => x.productPartId === data.productPartId)) {
      ElMessage.error("产品配件已存在");
      return;
    }
    productCheckPartList.value.push(data);
  } else {
    if (productCheckPartList.value.some(x => x.productPartId === data.productPartId && x.guid !== data.guid)) {
      ElMessage.error("产品配件已存在");
      return;
    }
    part.productPartId = data.productPartId;
    part.productPartName = data.productPartName;
    part.price = data.price;
    part.count = data.count;
    part.totalPrice = data.totalPrice;
  }
  createProductPartViewVisible.value = false;
}
const onUpdateProductPart = (row: { value: OrderProductCheckPriceDTO }) => {
  currentProductPart.value = row.value;
  createProductPartViewVisible.value = true;
}
const onDeleteProductPart = (row: { value: OrderProductCheckPriceDTO }) => {
  const data = row.value as OrderProductCheckPriceDTO;
  ElConfirm(`确定要删除配件【${data.productPartName}】`).then(() => {
    const index = productCheckPartList.value.findIndex(x => x.guid === data.guid);
    productCheckPartList.value.splice(index, 1);
  }).catch();
}
const onSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      // if (productCheckPartList.value.length === 0) {
      //   ElMessage.error("产品配件清单不能为空")
      //   return;
      // }
      const data = {
        ...form.value,
        quoteDate: form.value.quoteDate || DateUtil.default,
        quoteConfirmDate: form.value.quoteConfirmDate || DateUtil.default,
        orderId: props.orderId,
        productSn: props.productSn,
        fileIdList: imageIds.value,
        prices: productCheckPartList.value
      } as OrderProductCheckVO;
      const { success, msg } = !form.value.guid
        ? await ApiTree.afterSaleOrder.createCheckDetail(data)
        : await ApiTree.afterSaleOrder.updateCheckDetail(data)
      if (success) {
        ElMessage.success(msg)
        emits("close");
      }
    }
  })
}
/** 查询明细 */
const getProductCheckDetail = async () => {
  const { success, data } = await ApiTree.afterSaleOrder.getCheckDetail(props.orderId, props.productSn);
  if (success && data && data.check) {
    //
    form.value = data.check;
    productCheckPartList.value = data.prices;
    imageIds.value = data.fileIds;
  }
}
watch(() => props.visible, () => {
  if (props.visible) {
    getWarrantyList();
    getRepairSiteList();
    getProductCheckDetail();
  }
}, { immediate: true })
</script>
<style lang="scss" scope></style>
